package com.hyt.it.ogt.kq.common.gov.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *
 * </p>
 *
 * @author Chengxh
 * @since 2021-08-14
 */
@Slf4j
public class DownloadFileUtil {

    private static final int NEGATIVE_ONE = -1;

    private static final int BYTE = 1024;

    /**
     * 下载ClassPath文件
     * @param filePath 文件全路径
     * @param newName  下载的展示文件名
     * @return 响应
     */
    public static ResponseEntity<InputStreamResource> downloadClassPathResource(String filePath, String newName) {
        String path = null;
        ResponseEntity<InputStreamResource> response = null;
        try {
            path = filePath;
            ClassPathResource classPathResource = new ClassPathResource(path);
            InputStream inputStream = classPathResource.getInputStream();
            //File file = new File(path);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition",
                    "attachment; filename="
                            + new String(newName.getBytes("gbk"), "iso8859-1") + ".xlsx");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            response = ResponseEntity.ok().headers(headers)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(inputStream));
        } catch (FileNotFoundException e1) {
            log.error("找不到指定的文件", e1);
        } catch (IOException e) {
            log.error("获取不到文件流", e);
        }
        return response;
    }

    /**
     * 下载指定路径文件
     * @param request req
     * @param response resp
     * @param filePath 文件路径
     */
    public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String filePath) throws IOException {
        try {

            String userAgent = "User-Agent";
            String fireFox = "firefox";
            String utf8 = "UTF-8";
            String msie = "MSIE";
            String chrome = "CHROME";

            File file = new File(filePath);
            if (file.exists()) {
                String fileName  = file.getName();
                if (request.getHeader(userAgent).toLowerCase().indexOf(fireFox) > 0) {
                    //Firefox
                    fileName = new String(fileName.getBytes(utf8), "ISO8859-1");
                } else if (request.getHeader(userAgent).toUpperCase().indexOf(msie) > 0) {
                    //IE
                    fileName = URLEncoder.encode(fileName, utf8);
                } else if (request.getHeader(userAgent).toUpperCase().indexOf(chrome) > 0) {
                    //Chrome
                    fileName = new String(fileName.getBytes(utf8), "ISO8859-1");
                } else if (request.getHeader(userAgent).toLowerCase().contains(msie.toLowerCase())
                        ||
                        request.getHeader(userAgent).toLowerCase().contains("like gecko")) {
                    // win10 ie edge 浏览器 和其他系统的ie
                    fileName = URLEncoder.encode(fileName, utf8);
                }
                //首先设置响应的内容格式是force-download，那么你一旦点击下载按钮就会自动下载文件了
                response.setContentType("application/force-download");
                //通过设置头信息给文件命名，也即是，在前端，文件流被接受完还原成原文件的时候会以你传递的文件名来命名
                response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.setCharacterEncoding(utf8);
                //进行读写操作
                byte[] buffer = new byte[BYTE];
                try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) {
                    OutputStream os = response.getOutputStream();
                    //从源文件中读
                    int i = bis.read(buffer);
                    while (i != NEGATIVE_ONE) {
                        //写到response的输出流中
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (IOException e) {
                    log.error("downloadFile：", e);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}
